package com.ferry.wallpaper.controller;

import cn.hutool.core.io.IoUtil;
import com.ferry.wallpaper.domain.Comment;
import com.ferry.wallpaper.domain.User;
import com.ferry.wallpaper.domain.Wall;
import com.ferry.wallpaper.domain.view.WallView;
import com.ferry.wallpaper.service.CommentService;
import com.ferry.wallpaper.service.UserService;
import com.ferry.wallpaper.service.UserWallService;
import com.ferry.wallpaper.service.WallService;
import com.ferry.wallpaper.utils.StringUtils;
import com.ferry.wallpaper.utils.cg.ImageUtils;
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class ImageController {


    @Autowired
    private WallService wallService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserWallService userWallService;

    @Autowired
    private MinioClient client;

    @Autowired
    private CommentService commentService;


    @GetMapping("/image/{id}")
    public String image(@PathVariable Long id, Model model, HttpSession session) {

        Wall wall = wallService.get(id);
        WallView wallView = new WallView(wall);
        model.addAttribute("wallView",wallView);

        int downloadNumber = userWallService.getDownloadNumber(id);
        model.addAttribute("dl",downloadNumber);

        Object user = session.getAttribute("user");
        if (user instanceof User) {
            User ue = (User) user;
            User nu = userService.get(ue.getUserId());
            model.addAttribute("user",nu);
            List<Comment> comments = commentService.get(id);
            model.addAttribute("comments",comments);
        }
        return "image";
    }


    @PostMapping("/comment/{id}")
    public String comment(@PathVariable Long id,String comment,HttpSession session) {
        Object user = session.getAttribute("user");
        if (user instanceof User) {
            User ue = (User) user;
            if (!StringUtils.isEmpty(comment)) {
                commentService.insert(id, ue.getUserId(), ue.getUserNickname(), comment);
            }
        }
        return "redirect:/image/"+id;
    }

    @GetMapping("/get/{id}")
    public void get(@PathVariable Long id,HttpServletResponse response) throws Exception{
        Wall wall = wallService.get(id);

        URL url = new URL(wall.getWallPath());
        URLConnection urlConnection = url.openConnection();
        InputStream inputStream = urlConnection.getInputStream();
        byte[] bytes1 = IoUtil.readBytes(inputStream);


//        Image img = Img.from(inputStream).scale(0.3f).getImg();
//        img = ImgUtil.pressText(img, new String("摆渡村版权所有".getBytes(StandardCharsets.UTF_8)), Color.WHITE
//                , new Font("黑体", Font.BOLD, 30), 0, 0, 0.6f);
//        byte[] pngs = ImgUtil.toBytes(img, "png");

        BufferedImage image = ImageUtils.getImage(bytes1);
        byte[] bytes = ImageUtils.pressSign(ImageUtils.getBytes(image, "jpg"), "jpg", "摆渡村版权所有", 40);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    @GetMapping("/download/{id}")
    public String download(@PathVariable Long id, Model model, HttpSession session, HttpServletResponse response) {
        Object user = session.getAttribute("user");
        if (user instanceof User) {
            User ue = (User) user;
            User nu = userService.get(ue.getUserId());
            Wall wall = wallService.get(id);
            if (nu.getUserMoney() >= wall.getWallPrice()) {
                boolean buy = userService.buy(wall.getWallId(), nu.getUserId(), wall.getWallPrice());
                if (buy) {
                    // 开始下载
                    String wallPath = wall.getWallPath();
                    int i = wallPath.lastIndexOf('.');
                    String suffix = wallPath.substring(i+1);

                    try {
                        response.setContentType("application/x-download");
                        response.addHeader("Content-Disposition","attachment; filename=" +
                                URLEncoder.encode(wall.getWallName()+".jpg", "UTF-8"));

                        URL url = new URL(wall.getWallPath());
                        URLConnection urlConnection = url.openConnection();
                        InputStream inputStream = urlConnection.getInputStream();
                        byte[] rabbits = IoUtil.readBytes(inputStream);
                        response.setHeader("Content-Length", String.valueOf(rabbits.length));
                        ServletOutputStream outputStream = response.getOutputStream();
                        outputStream.write(rabbits);
                        inputStream.close();
                        return "redirect:/image/"+id;
                    } catch (Exception e){
                        return "redirect:/image/"+id;
                    }
                } else {
                    model.addAttribute("msg","购买失败");
                }

            } else {
                model.addAttribute("msg","C币不足，请充值");
            }
            WallView wallView = new WallView(wall);
            model.addAttribute("wallView",wallView);
            return "image";
        } else {
            return "redirect:/image/"+id;
        }
    }

}
